#include <QComboBox>
#include <QLineEdit>

#include "GY_TableViewItemDelegate.h"
#include "../GY_DelegateTableView.h"

GY_TableViewItemDelegate::GY_TableViewItemDelegate(GY_DelegateTableView *parent)
    : QStyledItemDelegate(parent)
{
    m_pTableView = parent;
}

QWidget *GY_TableViewItemDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    if(index.isValid()) {
        //判断是否存在该行该列的代理
        if(m_DelegateTypeMap.contains(index.data(GY_DelegateTableView::RowIdData)) || m_DelegateTypeMap.value(index.data(GY_DelegateTableView::RowIdData)).contains(index.column())) {
            if(GY_BaseDelegateWidget *editorWidget = newInstance(m_DelegateTypeMap.value(index.data(GY_DelegateTableView::RowIdData)).value(index.column()), parent); editorWidget != nullptr) {
                //保存窗口和索引
                m_Editor = editorWidget;
                m_Index = index;
                //初始化窗口
                return editorWidget;
            }
        }
    }

    return QStyledItemDelegate::createEditor(parent,option,index);
}

void GY_TableViewItemDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    if(GY_BaseDelegateWidget *editorWidget = qobject_cast<GY_BaseDelegateWidget*>(editor); editorWidget != nullptr) {
        //设置行列数
        editorWidget->setRowColumn(index.data(GY_DelegateTableView::RowIdData),index.column());
        //设置给窗口，让窗口初始化
        editorWidget->setData(index.data(GY_DelegateTableView::TransferData));
    }else {
        QStyledItemDelegate::setEditorData(editor,index);
    }
}

void GY_TableViewItemDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
    if(GY_BaseDelegateWidget *editorWidget = qobject_cast<GY_BaseDelegateWidget*>(editor); editorWidget != nullptr) {
        //给外部tableitem设置结构体
        model->setData(index,editorWidget->getData(),GY_DelegateTableView::TransferData);
        model->setData(index,editorWidget->getText(),GY_DelegateTableView::DisplayData);
        //重设文本信号
        emit dataChanged(editorWidget->getData(),index.data(GY_DelegateTableView::RowIdData),index.column());
    }else {
        QStyledItemDelegate::setModelData(editor,model,index);
        model->setData(index,qobject_cast<QLineEdit*>(editor)->text(),GY_DelegateTableView::TransferData);
        model->setData(index,qobject_cast<QLineEdit*>(editor)->text(),GY_DelegateTableView::DisplayData);
        emit dataChanged(qobject_cast<QLineEdit*>(editor)->text(),index.data(GY_DelegateTableView::RowIdData),index.column());
    }
}

void GY_TableViewItemDelegate::clickedBlack(QStandardItemModel *model)
{
    if(nullptr == m_pTableView->indexWidget(m_Index)) {
        //编辑器未打开返回
        return;
    }
    this->setModelData(m_Editor,model,m_Index);
    this->destroyEditor(m_Editor,m_Index);
}






